<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展 
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------

namespace app\admin\controller\wddj;

use addons\wddj\library\IDCardEncryptor;
use app\admin\model\wddj\Driver;
use app\api\model\wddj\UserWechat;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;

/**
 * 认证代驾
 *
 * @icon fa fa-circle-o
 */
class CertifiedDrivingAgent extends Backend
{

    /**
     * CertifiedDrivingAgent模型对象
     * @var \app\admin\model\wddj\CertifiedDrivingAgent
     */
    protected $model = null;
    protected $modelValidate = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wddj\CertifiedDrivingAgent;
        $this->view->assign("drivingExperienceList", $this->model->getDrivingExperienceList());
        $this->view->assign("driverLicenseTypeList", $this->model->getDriverLicenseTypeList());
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['wechat'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 审核
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function examine($ids = null)
    {
        $row = $this->model->get($ids);


        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row = $this->model->get($ids);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if ($params['state'] == 3 && empty($params['reject'])) {
            $this->error('请填写驳回原因');
        }
        $params = $this->preExcludeFields($params);
        $row = $this->model->get($ids);
        if ($params['state'] == '2') {//已通过
            $result = false;
            Db::startTrans();
            try {
                $result = $row->allowField(true)->save($params);
                $driverModel = new Driver();
                $create_data = array(
                    'wechat_id'=>$row['wechat_id'],
                    'certified_id' => $row['id'],
                    'channel' => '1',
                    'status'=>'normal',
                    'driver_lng'=>$row['longitude'],
                    'driver_lat'=>$row['latitude'],
                    'start_time'=>$row['start_time'],
                    'end_time'=>$row['end_time'],
                );
                $driverModel->data($create_data);
                $driverModel->allowField(true)->save();
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if (false === $result) {
                $this->error(__('No rows were updated'));
            }
        } elseif ($params['state'] == '3') {//已驳回
            $result = false;
            Db::startTrans();
            try {
                $result = $row->allowField(true)->save($params);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if (false === $result) {
                $this->error(__('No rows were updated'));
            }
        }
        $this->success();

    }

    /**
     * Desc 详情
     * Create on 2024/10/26 17:23
     * Create by wangyafang
     */
    public function details($ids = null)
    {
        $row = $this->model->get($ids);
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }
    //todo 后台添加，编辑

    /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
        $driverModel = new Driver();
        foreach ($list as $item) {
            $driverObj = $driverModel->where('wechat_id',$item['wechat_id'])->find();
            if (empty($driverObj)) {
                $this->error('司机姓名：'.$item['name'].'，未审核通过，无法操作');
            }
            unset($driverObj);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                $driverObj = $driverModel->where('wechat_id',$item['wechat_id'])->find();
                $count += $driverObj->allowField(true)->isUpdate(true)->save($values);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $id_card_pattern = '/^\d{17}[0-9xX]$/';
        if (!preg_match($id_card_pattern, $params['id_card'])) {
            $this->error('身份证号码格式不正确！');
        }

        $configObj = (new \app\api\model\wddj\Config())->get(1);
        $encryptor = new IDCardEncryptor($configObj['encryptor_key'],$configObj['encryptor_iv']);
        $params['id_card'] = $encryptor->encrypt($params['id_card']);
        $params['state'] = '2';
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            $driverModel = new Driver();
            $create_data = array(
                'wechat_id'=>$params['wechat_id'],
                'certified_id' => $this->model->id,
                'channel' => '2',
                'driver_lng'=>$params['longitude'],
                'driver_lat'=>$params['latitude'],
                'start_time'=>$params['start_time'],
                'end_time'=>$params['end_time'],
            );
            $driverModel->data($create_data);
            $driverModel->allowField(true)->save();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
//        $queryObj = $this->model
//            ->where('id','<>',$ids)
//            ->where('mobile',$params['mobile'])
//            ->find();
//        if ($queryObj) {
//            $this->error('手机号码被其他司机使用，请使用其他手机号');
//        }
        $id_card_pattern = '/^\d{17}[0-9xX]$/';
        if (!preg_match($id_card_pattern, $params['id_card'])) {
            $this->error('身份证号码格式不正确！');
        }
//        $userWechatObj = (new UserWechat())->where('mobile',$params['mobile'])->find();
//        if ($userWechatObj) {
//            $params['wechat_id'] = $userWechatObj['id'];
//        } else {
//            $params['wechat_id'] = 0;
//        }
        $configObj = (new \app\api\model\wddj\Config())->get(1);
        $encryptor = new IDCardEncryptor($configObj['encryptor_key'],$configObj['encryptor_iv']);
        $params['id_card'] = $encryptor->encrypt($params['id_card']);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            $driverModel = Driver::where('certified_id',$row['id'])->find();
            $create_data = array(
                'driver_lng'=>$params['longitude'],
                'driver_lat'=>$params['latitude'],
                'start_time'=>$params['start_time'],
                'end_time'=>$params['end_time'],
            );
            $driverModel->data($create_data);
            $driverModel->allowField(true)->save();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        //todo 待定，更新user表和user_wechat表里mobile，或者添加编辑时是否需要选择微信用户
        $this->success();
    }

    /**
     * Desc 选择微信用户
     * Create on 2024/11/6 16:25
     * Create by wangyafang
     */
    public function select_wechat()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $wechat_id_array = $this->model->where('wechat_id','<>',0)->column('wechat_id');
            $list = (new \app\api\model\wddj\UserWechat())
                ->where($where)
                ->where('id','not in',$wechat_id_array)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

}
